﻿using BCTMSRESTful.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BCTMSRESTful.Configs
{
    public class AddAuthTokenHeaderParameter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<OpenApiParameter>();
            }

            var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;

            if (descriptor == null)
            {
                return;
            }

            if (descriptor.ControllerTypeInfo.BaseType == typeof(Controller) || descriptor.ControllerTypeInfo.BaseType == typeof(BCTMSRESTfulAPIController))
            {
                return;
            }

            bool isAnonymous = descriptor.MethodInfo.GetCustomAttributes(true).Any(p => p is AllowAnonymousAttribute);

            // 非匿名的方法，链接中添加 AccessToken 值
            if (!isAnonymous)
            {
                operation.Parameters.Insert(0, new OpenApiParameter
                {
                    Name = "authorization",
                    In = ParameterLocation.Header,//query header body path formData
                    Style = ParameterStyle.Simple,
                    Description = "访问令牌。",
                    Required = true //是否必选
                });
            }
        }
    }
}
